from collections import defaultdict
from main import Fact,Thing,Question,Answer

def initialize_fact_declined():
	for f in Fact.all():
		if f.declined!=True:
			f.declined=False
			f.put()
			
def refresh_question_answer_counts():
	q_counts=defaultdict(int)
	a_counts=defaultdict(int)
	things={}
	for f in Fact.all():
		t_key=str(f.thing.key())
		q_key=f.questions[0]
		if f.answers:
			a_key=f.answers[0]
		else:
			a_key=None
		q_counts[q_key]+=1
		a_counts[a_key]+=1
		if t_key not in things:
			things[t_key]={"questions":[],"answers":[]}
		if q_key not in things[t_key]['questions']:
			things[t_key]['questions'].append(q_key)
		if a_key and a_key not in things[t_key]['answers']:
			things[t_key]['answers'].append(a_key)
	for t in Thing.all():
		if str(t.key()) in things:
			t.questions=things[str(t.key())]["questions"]
			t.answers=things[str(t.key())]["answers"]
			t.put()
	for q in Question.all():
		q.count=q_counts[q.key().name()]
		q.put()
	for a in Answer.all():
		a.count=a_counts[a.key().name()]
		a.put()
	return(q_counts,a_counts,things)